<script setup name="updateDialog" lang="ts">
import { ref, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { loginAddApi, loginUpdateApi } from '@/apis/user'

interface Props {
  visible: boolean,
  info: {
    type: object,
    default: () => void
  },
  
  /** 部门列表 */
  deptList: {
    type: Array<{_id: string, deptName: string}>,
    default: () => void
  }
}

const props = defineProps<Props>()
const emit = defineEmits(['confirm', 'update:visible'])

watch(props, (prop) => {
  if (prop.visible && prop.info._id) {
    formData.value = {...prop.info, id: prop.info._id}
  }
})

/** form 表单 */
const formData = ref({
  account: '',
  password: '',
  nickname: '',
  gender: 1,
  auth: 2,
  departmentIds: []
})

/** 关闭弹窗 */
const handleClose = () => {
  formData.value = {
      account: '',
      password: '',
      nickname: '',
      gender: 1,
      auth: 2,
      departmentIds: []
  }
  emit('update:visible', false)
}

const handleConfirm = async () => {
  const api = formData.value.id? loginUpdateApi : loginAddApi
  await api(formData.value)
  ElMessage.success('操作成功')
  emit('confirm')
  handleClose()
}
</script>

<template>
  <el-dialog :model-value="visible" title="修改基础配置" width="500" @close="handleClose">
    <!-- 对话框内容插槽 -->
    <el-form>
      <el-form-item label="账号">
        <el-input v-model="formData.account" placeholder="请输入账号" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="formData.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="formData.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="部门">
        <el-select
          v-model="formData.departmentIds"
          multiple
          placeholder="请选择所属部门"
          style="width: 100%"
        >
          <el-option
            v-for="item in props.deptList"
            :key="item._id"
            :label="item.deptName"
            :value="item._id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="formData.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="权限">
        <el-radio-group v-model="formData.auth">
          <el-radio :label="1">超级管理员</el-radio>
          <el-radio :label="2">普通管理员</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <!-- 自定义底部按钮 -->
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
